package simpleEventBus

import (
	"go-ddd-ecommerce/internal/domain/events"
	"log"
)

// SimpleEventBus 简单事件总线实现(内存版)
type SimpleEventBus struct {
	handlers map[string][]events.EventHandler
}

func NewSimpleEventBus() *SimpleEventBus {
	return &SimpleEventBus{
		handlers: make(map[string][]events.EventHandler),
	}
}

// Publish 发布事件
func (b *SimpleEventBus) Publish(event events.DomainEvent) error {
	eventType := event.EventName()
	if handlers, exists := b.handlers[eventType]; exists {
		for _, handler := range handlers {
			//异步处理事件，不阻塞主流程
			go func(h events.EventHandler, e events.DomainEvent) {
				if err := h.Handle(e); err != nil {
					// 这里可以添加重试机制或死信队列处理
					// 目前简单记录日志
					log.Printf("事件处理失败: %v, 事件: %v", err, e)
				}
			}(handler, event)
		}
	}
	return nil
}

// Subscribe 订阅事件
func (b *SimpleEventBus) Subscribe(eventType string, handler events.EventHandler) {
	b.handlers[eventType] = append(b.handlers[eventType], handler)
}

// Unsubscribe 取消订阅
func (b *SimpleEventBus) Unsubscribe(eventType string, handler events.EventHandler) {
	if handlers, exists := b.handlers[eventType]; exists {
		for i, h := range handlers {
			if h == handler {
				b.handlers[eventType] = append(handlers[:i], handlers[i+1:]...)
				break
			}
		}
	}
}
